package com.coderside.fragment.thread.ABC;

import java.util.LinkedList;
import java.util.concurrent.CountDownLatch;

public class ThreadPrintABC_4 {
	static int circleNum = 100;
	final static CountDownLatch c = new CountDownLatch(3 * circleNum);

	public static void main(String[] args) {
		long a = System.currentTimeMillis();
		Lock lock = new Lock();
		MyThread t1 = new MyThread("A", lock, circleNum, c);
		MyThread t2 = new MyThread("B", lock, circleNum, c);
		MyThread t3 = new MyThread("C", lock, circleNum, c);
		new Thread(t1).start();
		new Thread(t2).start();
		new Thread(t3).start();
		try {
			c.await();
			long b = System.currentTimeMillis();
			System.out.println(b - a);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

// 线程
class MyThread implements Runnable {

	String key = null;
	Lock lock = null;
	int num = 0;
	private CountDownLatch countdownlatch;

	public MyThread(String k, Lock l, int n, CountDownLatch c) {
		key = k;
		lock = l;
		num = n;
		countdownlatch = c;
	}

	public void run() {
		while (num > 0) {
			synchronized (lock) {
				if (key == lock.queue.getFirst()) {
					System.out.print(key);
					countdownlatch.countDown();
					lock.next();
					num--;
				}
			}
		}
	}
}

// 锁功能
class Lock {
	LinkedList<String> queue;// 模仿循环队列

	Lock() {
		queue = new LinkedList<String>();
		queue.add("A");
		queue.add("B");
		queue.add("C");
	}

	void next() {
		String h = queue.poll();
		queue.add(h);
	}

}